package com.jh.complicate.socket.doubleside;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author JH_Wong
 * @projectName newforward
 * @title ServerSocketDemo.java
 * @package com.jh.complicate.socket.doubleside
 * @description 双向通信socket
 * @date 2019-05-31 17:48
 */
public class ServerSocketDemo {
    public static void main(String[] args) {
        try {
            ServerSocket server = new ServerSocket(9898);
            // 阻塞获取客户端发来的请求
            Socket socket = server.accept();

            // 读取客户端发来的消息
            BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //System.out.println("Client：" + is.read());

            String line;
            PrintWriter os = new PrintWriter(socket.getOutputStream(), true);
            // 获取控制台输入的
            BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
            line = sin.readLine();
            while (true) {
                if (!line.equals("bye")) {
                    // 写到客户端
                    os.print(line);
                    System.out.println("Server：" + line);
                } else {
                    break;
                }

                line = sin.readLine();

                System.out.println("Client：" + is.readLine());
            }

            sin.close();
            os.close();
            is.close();
            socket.close();
            server.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
